package team.seekers.hula.system.order.service;

import com.lly835.bestpay.enums.BestPayTypeEnum;
import com.lly835.bestpay.model.PayRequest;
import com.lly835.bestpay.model.PayResponse;
import com.lly835.bestpay.service.BestPayService;
import com.lly835.bestpay.utils.JsonUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import team.seekers.hula.user.user.service.UserService;

/**
 * @author hbc
 */
@Slf4j
@Service
public class PaymentService {

    @Autowired
    private UserService userService;

    @Autowired
    private BestPayService bestPayService;

    public PayResponse pay(String orderId,Double money,BestPayTypeEnum payType,String userId) {
        //支付请求参数
        PayRequest request = new PayRequest();
        request.setPayTypeEnum(payType);
        request.setOrderId(orderId);
        request.setOrderAmount(money);

        request.setOrderName("科兴创达");
        if(payType.equals(BestPayTypeEnum.WXPAY_MINI) || payType.equals(BestPayTypeEnum.WXPAY_MP)){
            String openId = userService.queryOpenIdByIdAndPayType(userId,payType);
            request.setOpenid(openId);
        }
        request.setAttach("课程购买支付");

        log.info("【发起支付】request={}", JsonUtil.toJson(request));
        PayResponse payResponse = bestPayService.pay(request);

        if(payType.equals(BestPayTypeEnum.WXPAY_MWEB)){
            payResponse.setCodeUrl(String.format("https://wx.tenpay.com/cgi-bin/mmpayweb-bin/checkmweb?prepay_id=%s&package=%s",
                    payResponse.getPrepayId(),
                    payResponse.getPackAge()));
        }

        log.info("【发起支付】response={}", JsonUtil.toJson(payResponse));
        return payResponse;
    }

}
